package cs.java.json;

import static cs.java.lang.Lang.is;
import static cs.java.lang.Lang.json;
import static cs.java.lang.Lang.no;

import cs.java.collections.List;

public abstract class JSONDataBase implements JSONData {
	protected JSONObject data;

	protected String getAsString(String key) {
		return data.get(key).getValue() + "";
	}

	protected Boolean getBoolean(String key) {
		return data.getBoolean(key);
	}

	protected Integer getNumberInt(String key) {
		Double number = data.getNumber(key);
		if (no(number)) return null;
		return number.intValue();
	}

	protected String getNumberIntString(String key) {
		return data.getNumber(key).intValue() + "";
	}

	protected String getNumberString(String key) {
		return getString(key) + "";
	}

	protected String getString(String key) {
		return data.getString(key);
	}

	protected <T extends JSONData> T load(T data, JSONObject object) {
		data.load(object);
		return data;
	}

	protected <T extends JSONData> T load(T apiData, JSONObject jsonData, String id) {
		apiData.load(jsonData.getObject(id));
		return apiData;
	}

	protected void loadStrings(List<String> list, JSONObject data, String id) {
		if (data.contains(id)) for (JSONType type : data.getArray(id))
			list.add(type.asString());
	}

	protected void onLoad(JSONObject data) {}

	protected void onSave(JSONObject data) {}

	protected void save(JSONObject object, String id, Double string) {
		if (is(string)) object.put(id, string);
	}

	protected void save(JSONObject object, String id, JSONDataBase data) {
		if (is(data)) object.put(id, data.save());
	}

	protected void save(JSONObject object, String id, String string) {
		if (is(string)) object.put(id, string);
	}

	public void load(JSONObject data) {
		if (no(data)) return;
		this.data = data;
		onLoad(data);
	}

	public final JSONObject save() {
		if (no(data)) data = json().createObject();
		onSave(data);
		return data;
	}
}
